<?php
require_once __DIR__ . '/../../functions.php';

header('Content-Type: application/json');

// 检查管理员权限
if (!isAdmin()) {
    echo json_encode(['success' => false, 'message' => '您没有权限执行此操作']);
    exit;
}

$settlementId = intval($_GET['id'] ?? 0);

if ($settlementId <= 0) {
    echo json_encode(['success' => false, 'message' => '结算记录ID无效']);
    exit;
}

// 获取结算详情
$db = getDB();
$stmt = $db->prepare("SELECT s.*, u.username, u.phone, u.group_name, u.wechat_account, u.alipay_account, u.wechat_nickname FROM settlements s 
                     LEFT JOIN users u ON s.user_id = u.id 
                     WHERE s.id = ?");
$stmt->execute([$settlementId]);
$settlement = $stmt->fetch();

if (!$settlement) {
    echo json_encode(['success' => false, 'message' => '结算记录不存在']);
    exit;
}

// 获取群组名称标签
$settlement['group_name_label'] = getConfigOptionLabel('group_name', $settlement['group_name']);

// 修复：正确处理结算截图
$settlement['settlement_screenshots'] = [];
$screenshotsField = $settlement['settlement_screenshots'] ?? ''; // 先保存原始字段值

if (!empty($screenshotsField)) {
    $screenshots = json_decode($screenshotsField, true);
    if (is_array($screenshots) && !empty($screenshots)) {
        foreach ($screenshots as $screenshot) {
            if (!empty($screenshot)) {
                $settlement['settlement_screenshots'][] = [
                    'filename' => $screenshot,
                    'url' => UPLOAD_URL . 'settlements/' . $screenshot
                ];
            }
        }
    }
}

// 获取关联的订单详情（去重显示）
$orderIds = json_decode($settlement['order_ids'], true) ?: [];
$orders = [];

if (!empty($orderIds)) {
    $placeholders = str_repeat('?,', count($orderIds) - 1) . '?';
    $stmt = $db->prepare("SELECT o.* FROM orders o WHERE o.id IN (" . $placeholders . ")");
    $stmt->execute($orderIds);
    $orders = $stmt->fetchAll();
    
    // 处理订单的标签
    foreach ($orders as &$order) {
        $order['delivery_location_label'] = getConfigOptionLabel('delivery_location', $order['delivery_location']);
        $order['order_platform_label'] = getConfigOptionLabel('order_platform', $order['order_platform']);
        if ($order['order_screenshot']) {
            $order['screenshot_url'] = UPLOAD_URL . 'orders/' . $order['order_screenshot'];
        }
    }
}

// 获取结算明细记录（显示每次结算的详细信息）
$settlementDetails = getSettlementDetails($settlementId);

// 处理结算明细的截图
foreach ($settlementDetails as &$detail) {
    $detail['screenshot_urls'] = [];
    if (!empty($detail['screenshots'])) {
        $screenshots = json_decode($detail['screenshots'], true);
        if (is_array($screenshots) && !empty($screenshots)) {
            foreach ($screenshots as $screenshot) {
                if (!empty($screenshot)) {
                    $detail['screenshot_urls'][] = [
                        'filename' => $screenshot,
                        'url' => UPLOAD_URL . 'settlements/' . $screenshot
                    ];
                }
            }
        }
    }
}

$settlement['orders'] = $orders;
$settlement['order_count'] = count($orders);
$settlement['settlement_details'] = $settlementDetails;
$settlement['detail_count'] = count($settlementDetails);

echo json_encode(['success' => true, 'data' => $settlement]);
?>